<template>
  <div>
    <statistic-head :page="page"></statistic-head>
    <el-scrollbar
      wrapClass="scrollbar-wrap"
      :style="{
        height: scrollHeight,
        // width: scrollWidth
      }"
      ref="scrollbarContainer">
      <div id="home">
        <div style="background-color: white">
          <div class="head">
            <el-row style="padding-bottom: 10px">
              <el-col :span="4" style="padding: 10px">
                <li style="font-size: 15px">
                  当前总能耗：{{totalEC}}度
                </li>
              </el-col>
              <div v-for="item in eC">
                <el-col :span="4" style="padding: 10px">
                  <li style="font-size: 15px">
                    {{item.name}}：{{item.consume}}度
                  </li>
                </el-col>
              </div>
            </el-row>
          </div>
          <el-row style="padding-bottom: 60px">
            <el-col :span="10" :offset="1">
              <el-row :gutter="20" style="padding-bottom: 20px">
                <el-col :span="12">
                  <div style="margin: 0 0 0 100px">
                    <li class="el-icon-info">当&#12288;周</li>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <template>
                  <ve-pie :data="chartData_week" :events="chartEvent_week"></ve-pie>
                </template>
              </el-row>
              <el-row>
                <el-col :span="8" :offset="8">
                  <li style="font-size: 15px;text-align: center">能耗:{{sum_week}}度</li>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-row :gutter="20" style="padding-bottom: 20px">
                <el-col :span="12">
                  <div style="margin: 0 0 0 100px">
                    <li class="el-icon-info">当&#12288;月</li>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <template>
                  <ve-pie :data="chartData_month" :events="chartEvent_month"></ve-pie>
                </template>
              </el-row>
              <el-row>
                <el-col :span="8" :offset="8">
                  <li style="font-size: 15px;text-align: center">能耗:{{sum_month}}度</li>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row style="padding: 0 0 0 16px">
            <el-col :span="10" :offset="1">
              <el-row :gutter="20" style="padding-bottom: 20px">
                <el-col :span="12">
                  <div style="margin: 0 0 0 100px">
                    <li class="el-icon-info">当季度</li>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <template>
                  <ve-pie :data="chartData_quarter" :events="chartEvent_quarter"></ve-pie>
                </template>
              </el-row>
              <el-row>
                <el-col :span="8" :offset="8">
                  <li style="font-size: 15px;text-align: center">能耗:{{sum_quarter}}度</li>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-row :gutter="20" style="padding-bottom: 20px">
                <el-col :span="12">
                  <div style="margin: 0 0 0 100px">
                    <li class="el-icon-info">当&#12288;年</li>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <template>
                  <ve-pie :data="chartData_year" :events="chartEvent_year"></ve-pie>
                </template>
              </el-row>
              <el-row style="padding-bottom: 60px">
                <el-col :span="8" :offset="8">
                  <li style="font-size: 15px;text-align: center">能耗:{{sum_year}}度</li>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-scrollbar>
    <detail-dialog
      :showDetailDialog="showDetailDialog"
      :tableData="tableData"
      :maxEc="maxEc"
      :minEc="minEc"
      :avgEc="avgEc"
      @closeModel="closeModel"></detail-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import Axios from 'axios'
  import VeLine from 'v-charts/lib/line.common'
  import VeHistogram from 'v-charts/lib/histogram.common'
  import VePie from 'v-charts/lib/pie.common'
  import VeChart from 'v-charts/lib/chart'
  import statisticHead from "./componet/statisticHead"
  import detailDialog from "./componet/detailDialog"

  export default {
    components: {
      VeLine,
      VeHistogram,
      VePie,
      VeChart,
      statisticHead,
      detailDialog
    },

    data() {
      this.extend = {
        'xAxis.0.axisLabel.rotate': 45
      }
      let self = this
      let date = new Date()
      let startTime = ''
      let day = date.getDay()//周几
      let result = date.getDate()-day+1
      let month = date.getMonth() + 1
      let year = date.getFullYear()
      this.chartEvent_week = {
        click: function (e) {
          self.getDeviceTypeId(e.name)
          if (result <= 0 && month <= 1) {
            startTime = (year-1) + '-' + month + '-' + (self.xMonth[12]+result)
          } else if (result <= 0 && month === 3 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0)) {
            startTime = year + '-' + (month-1) + '-' + (self.yMonth[month-1]+result)
          } else if (result <= 0) {
            startTime = year + '-' + (month-1) + '-' + (self.xMonth[month-1]+result)
          } else if (day==1) {
            startTime = year + '-' + month + '-' + date.getDate()
          } else {
            startTime = year + '-' + month + '-' + result
          }
          console.log(startTime)
          self.getTableDate(startTime,self.deviceTypeId,1)
          self.showDetailDialog = true
        }
      }
      this.chartEvent_month = {
        click: function (e) {
          self.getDeviceTypeId(e.name)
          self.getTableDate(year+'-'+(month)+'-'+'01',self.deviceTypeId,2)
          self.showDetailDialog = true
        }
      }
      this.chartEvent_quarter = {
        click: function (e) {
          let dateTime = ''
          self.getDeviceTypeId(e.name)
          if (month>=1&&month<=3){
            dateTime = year+'-01-01'
          } else if (month>=4&&month<=6){
            dateTime = year+'-04-01'
          } else if (month>=7&&month<=9){
            dateTime = year+'-07-01'
          } else if (month>=10&&month<=12){
            dateTime = year+'-10-01'
          }
          console.log(dateTime)
          self.getTableDate(dateTime,self.deviceTypeId,3)
          self.showDetailDialog = true
        }
      }
      this.chartEvent_year = {
        click: function (e) {
          self.getDeviceTypeId(e.name)
          self.getTableDate(year+'-01-01',self.deviceTypeId,4)
          self.showDetailDialog = true
        }
      }
      return {
        page: '默认显示',

        chartData_week: {
          columns:['类型','能耗'],
          rows: []
        },
        chartData_month: {
          columns:['类型','能耗'],
          rows: []
        },
        chartData_quarter: {
          columns:['类型','能耗'],
          rows: []
        },
        chartData_year: {
          columns:['类型','能耗'],
          rows: []
        },
        scrollHeight: '0px',
        startTime: '',
        endTime: '',
        totalEC: 4396,
        eC: [],
        sum_week: 0,
        sum_month: 0,
        sum_quarter: 0,
        sum_year: 0,

        week: '',
        showDetailDialog: false,

        tableData: [],
        deviceTypes: [],
        deviceTypeId: '',
        maxEc: '',
        minEc: '',
        avgEc: '',

        week: [
          {day: '周一'},
          {day: '周二'},
          {day: '周三'},
          {day: '周四'},
          {day: '周五'},
          {day: '周六'},
          {day: '周日'}
        ],
        quarter: ['1-3','4-6','7-9','10-12'],
        xMonth: {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31},
        yMonth: {1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
      }
    },
    methods:{
      initOptions2($event) {
        //设置结束时间时间范围
        console.log($event.getTime());
        console.log(Date.now());
        this.pickerOptions2 = {
          disabledDate(time) {
            return time.getTime() < $event.getTime() - 8.64e7 + 1;
          }
        };
      },

      //数据统计
      getData(){
        let self = this
        Axios.get(this.api+'getECOfTime',{
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          let sum = 0
          res.data.total.forEach(item => {
            console.log(item.electricConsume)
            let temp = {}
            temp['name'] = item.deviceTypeName
            temp['consume'] = item.electricConsume
            if (item.electricConsume!== undefined){
              sum += item.electricConsume
            }
            self.eC.push(temp)
          })
          self.totalEC = sum

          res.data.currentWeek.forEach(item =>{
            if (item.electricConsume!== undefined){
              self.sum_week += item.electricConsume
            }
            self.chartData_week.rows.push({'类型':item.deviceTypeName,'能耗':item.electricConsume})
          })
          res.data.currentMonth.forEach(item =>{
            if (item.electricConsume!== undefined){
              self.sum_month += item.electricConsume
            }
            self.chartData_month.rows.push({'类型':item.deviceTypeName,'能耗':item.electricConsume})
          })
          res.data.currentSeason.forEach(item =>{
            if (item.electricConsume!== undefined){
              self.sum_quarter += item.electricConsume
            }
            self.chartData_quarter.rows.push({'类型':item.deviceTypeName,'能耗':item.electricConsume})
          })
          res.data.currentYear.forEach(item =>{
            if (item.electricConsume!== undefined){
              self.sum_year += item.electricConsume
            }
            self.chartData_year.rows.push({'类型':item.deviceTypeName,'能耗':item.electricConsume})
          })
        })
      },
      getTableDate(startTime,type,index){
        let self = this
        let date = new Date()
        console.log(startTime)
        Axios.get(this.api+'getECOfDevice',{
          params:{
            deviceTypeId: type,
            startTime: startTime,
            endTime: date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()
          },
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          self.maxEc = res.data.total.maxEC
          self.minEc = res.data.total.minEC
          self.avgEc = res.data.total.avgEC
          // console.log(res.data.device.length)
          res.data.device.forEach(item =>{
            console.log(item.ECOfDay.length)
            let table = []
            switch (index) {
              case 1:
                let num = 0
                self.week.forEach(obj => {
                  if (num<item.ECOfDay.length) {
                    table.push({'日期':obj.day,'能耗': item.ECOfDay[num].electricConsume})
                    console.log(num+obj.day+'-_-'+item.ECOfDay[num].electricConsume)
                    num++
                  } else {
                    table.push({'日期':obj.day,'能耗': 0})
                  }
                })
                break
              case 2:
                item.ECOfDay.forEach(ec => {
                  let date = ec.createTime.split(' ')[0].split('-')[1]+'-'+ec.createTime.split(' ')[0].split('-')[2]
                  table.push({'日期':date,'能耗': ec.electricConsume})
                })
                break
              case 3:
                Axios.get(this.api+'getMonthECByDeviceId',{
                  params: {
                    deviceId: item.deviceId,
                    startTime: startTime,
                    endTime: date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()
                  },
                  headers: {'X-Requested-With': 'XMLHttpRequest'},
                  withCredentials: true
                }).then(res => {
                  res.data.ECList.forEach(item => {
                    table.push({'日期':item.month,'能耗':item.EC})
                  })
                })
                break
              case 4:
                Axios.get(this.api+'getMonthECByDeviceId',{
                  params: {
                    deviceId: item.deviceId,
                    startTime: startTime,
                    endTime: date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()
                  },
                  headers: {'X-Requested-With': 'XMLHttpRequest'},
                  withCredentials: true
                }).then(res => {
                  res.data.ECList.forEach(item => {
                    table.push({'日期':item.month,'能耗':item.EC})
                  })
                })
                break
            }
            self.tableData.push({
              name: item.deviceName,
              num: item.subEquipment,
              type: item.deviceTypeName,
              totalEc: item.EC,
              model: item.brandName+item.modelName,
              ip: item.ipAddress,
              port: item.port,
              id: item.deviceId,
              location: item.zoneName+item.buildingName+item.roomName,
              building: item.buildingName,
              room: item.roomName,
              roomType: item.roomTypeName,
              dept: item.deptName,
              addressCode: item.addressCode,
              chartData: {
                columns: ['日期','能耗'],
                rows: table
              }
            })
          })
        })
      },
      getDeviceTypes(){
        let self = this
        self.deviceTypes = []
        Axios.get(this.api+'types',{
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          self.deviceTypes = res.data
          console.log(self.deviceTypes)
        })
      },
      getDeviceTypeId(name){
        this.deviceTypes.forEach(type => {
          if (type.name === name){
            this.deviceTypeId = type.id
          }
        })
      },

      closeModel(){
        this.tableData = []
        this.showDetailDialog = false
      }
    },
    mounted(){
      this.scrollHeight = window.innerHeight + 'px'
      this.getData()
      this.getDeviceTypes()
    },
    watch:{
      radio(newVal){
        console.log(newVal)
        this.chartSettingsMonth.type = newVal
      }
    }
  }
</script>

<style>
  .el-scrollbar__wrap{
    height: 90%;
    overflow-x: hidden;
  }
  /*.scrollbar-wrap{*/
  /*  overflow-x: hidden;*/
  /*}*/
</style>
